# IOU
# 并集除以交集
import matplotlib.pyplot as plt
import matplotlib.patches as mpathes
import torch


# 需要增加一个 最小面积运算
def myIOU(pic0xy, pic1xy, useMinIou=False):
    """
    :param pic0xy: 第一张图片左上角坐标和右下角坐标，输入格式必须为元组，里面存放的格式为x0,y0,x1,y1
    :param pic1xy: 第二张图片左上角坐标和右下角坐标
    :return:
    """
    # 左上角x,y，要分别取，反正就是取左上角坐标中大的那个
    minx = torch.max(pic0xy[:, 0], pic1xy[:, 0])
    miny = torch.max(pic0xy[:, 1], pic1xy[:, 1])
    maxx = torch.min(pic0xy[:, 2], pic1xy[:, 2])
    maxy = torch.min(pic0xy[:, 3], pic1xy[:, 3])
    # 算交集面积 长宽
    awidth = maxx - minx
    aheight = maxy - miny
    awidth[awidth <= 0] = 0
    aheight[aheight <= 0] = 0
    area1 = (awidth) * (aheight)

    # 是否取较小值，并集除以较小值
    if useMinIou:
        # 计算交集 除以较小面积，大框套下框的情况
        pt0area = (pic0xy[:, 2] - pic0xy[:, 0]) * (pic0xy[:, 3] - pic0xy[:, 1])
        pt1area = (pic1xy[:, 2] - pic1xy[:, 0]) * (pic1xy[:, 3] - pic1xy[:, 1])
        minarea = torch.min(pt0area, pt1area)
        return area1 / minarea
    else:
        # 算并集面积 各自面积相加-交集
        area2 = (pic0xy[:, 2] - pic0xy[:, 0]) * (pic0xy[:, 3] - pic0xy[:, 1]) + (pic1xy[:, 2] - pic1xy[:, 0]) * (
                    pic1xy[:, 3] - pic1xy[:, 1]) - area1
        return area1 / area2


if __name__ == "__main__":
    pic0 = torch.tensor([[0, 10, 10, 20], [0, 10, 50, 20]], dtype=torch.float32)
    pic1 = torch.tensor([[1, 10, 5, 20]], dtype=torch.float32)

    print(myIOU(pic0, pic1, True))
